from openpyxl.chart import (
    DoughnutChart,
    Reference,
    Series,
)
from openpyxl import Workbook
from openpyxl.chart.series import DataPoint

# 准备数据
data = [
    ['Pie', 2014, 2015],
    ['Plain', 40, 50],
    ['Jam', 2, 10],
    ['Lime', 20, 30],
    ['Chocolate', 30, 40],
]

# 工作表
wb = Workbook()
ws = wb.active

# 将数据追加到工作表
for row in data:
    ws.append(row)

# 创建甜甜圈图
chart = DoughnutChart()
# 标签
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
# 数据
data = Reference(ws, min_col=2, min_row=1, max_row=5)
# 添加数据
chart.add_data(data, titles_from_data=True)
# 添加分类
chart.set_categories(labels)
# 设置标题
chart.title = "甜甜圈图"
chart.style = 26

# Cut the first slice out of the doughnut
# 切割点
slices = [DataPoint(idx=i) for i in range(4)]
# 每一种数据的切割大小
plain, jam, lime, chocolate = slices
# 设置系列0的切割点
chart.series[0].data_points = slices
# 设置不同的颜色
plain.graphicalProperties.solidFill = "FAE1D0"
jam.graphicalProperties.solidFill = "BB2244"
lime.graphicalProperties.solidFill = "22DD22"
chocolate.graphicalProperties.solidFill = "61210B"
# 偏移
chocolate.explosion = 10
# 将甜甜圈图添加到工作表
ws.add_chart(chart, "E1")

# 创建第二个图表
from copy import deepcopy

chart2 = deepcopy(chart)
chart2.title = None
data = Reference(ws, min_col=3, min_row=1, max_row=5)
series2 = Series(data, title_from_data=True)
series2.data_points = slices
chart2.series.append(series2)
ws.add_chart(chart2, "E17")

wb.save("doughnut.xlsx")
